from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Permission, Group
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpRequest, HttpResponse
from LogisticsCard.models import Log
from LogisticsCard.permission_dict import permission_cn

# 角色管理相关视图
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpRequest, HttpResponse

@login_required

def roles_view(request: HttpRequest) -> HttpResponse:
    """
    角色视图，展示所有角色信息。
    :param request: HttpRequest对象
    :return: 渲染角色列表页面
    """
    roles = Group.objects.all()
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    paginator = Paginator(roles, 10)
    page = request.GET.get('page')
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    return render(request, 'roles/index.html', {'page_obj': page_obj})


@login_required
def add_role_view(request: HttpRequest) -> HttpResponse:
    """
    添加角色视图，处理角色表单提交。
    :param request: HttpRequest对象
    :return: 渲染角色添加页面或跳转到角色列表
    """
    permissions = Permission.objects.all()
    if request.method == 'POST':
        name = request.POST.get('name')
        perm_ids = request.POST.getlist('permissions')
        if not Group.objects.filter(name=name).exists():
            group = Group.objects.create(name=name)
            group.permissions.set(Permission.objects.filter(id__in=perm_ids))
            group.save()
            Log.objects.create(user=request.user, action='add_role', detail=f'添加角色:{group.name}')
            return redirect('/roles/')
        else:
            return render(request, 'roles/add.html', {'error': '角色名称已存在', 'permissions': permissions, 'perm_cn': permission_cn})
    return render(request, 'roles/add.html', {'permissions': permissions, 'perm_cn': permission_cn})


@login_required
def edit_role_view(request: HttpRequest, role_id: int) -> HttpResponse:
    """
    编辑角色视图，处理角色信息更新。
    :param request: HttpRequest对象
    :param role_id: 角色ID
    :return: 渲染角色编辑页面或跳转到角色列表
    """
    role = Group.objects.get(id=role_id)
    permissions = Permission.objects.all()
    if request.method == 'POST':
        role.name = request.POST.get('name')
        perm_ids = request.POST.getlist('permissions')
        role.permissions.set(Permission.objects.filter(id__in=perm_ids))
        role.save()
        Log.objects.create(user=request.user, action='edit_role', detail=f'编辑角色:{role.name}')
        return redirect('/roles/')
    return render(request, 'roles/edit.html', {'role': role, 'permissions': permissions, 'perm_cn': permission_cn})


@login_required
def delete_role_view(request: HttpRequest, role_id: int) -> HttpResponse:
    """
    删除角色视图，处理角色删除请求。
    :param request: HttpRequest对象
    :param role_id: 角色ID
    :return: 跳转到角色列表
    """
    role = get_object_or_404(Group, id=role_id)
    role_name = role.name
    role.delete()
    Log.objects.create(user=request.user, action='other', detail=f'删除角色:{role_name}')
    return redirect('/roles/')
